package unilearn.generate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.SQLException;

/*
 * GenerateSubmission.java
 *
 * Created on 29 April 2008, 21:39
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 * @author Ben
 */
public class GenerateSubmission
{

	public static final String INSERT_SUBMISSION = "INSERT INTO submission (assignment_id,date_submitted,student_number,file_id) "
			+ "VALUES (%1,'2008-04-12 12:00:00','%2',%3);";

	public static final String OUTPUT_FILE = "test/dbSubmissionTest.art";

	private final PrintWriter writer;

	private PrintWriter createWriter;

	private final GenerateFileData fileGen;

	private long submissionsCreated = 0;

	/** Creates a new instance of GenerateSubmission */
	public GenerateSubmission(GenerateFileData fileGen, PrintWriter writer)
			throws FileNotFoundException
	{
		this.fileGen = fileGen;
		this.writer = writer;

		File outputFile = new File(OUTPUT_FILE);
		if (outputFile.exists()) outputFile.delete();

		FileOutputStream fos = new FileOutputStream(outputFile);
		createWriter = new PrintWriter(new OutputStreamWriter(fos));
		System.out.println("Exporting ART Submission Create/Destroy TestCase to "
				+ outputFile.getAbsolutePath());
	}

	public void addSubmissions(long assignmentID, String[] subjectStudents)
		throws SQLException
	{
		/* Add Students */
		int created = 0;
		for (int i = 0; i < subjectStudents.length; i++)
		{
			int studentSubmitted = (int) (Math.random() * 7.0);
			if (studentSubmitted < 5)
			{
				created++;
				addSubmission(assignmentID, subjectStudents[i]);
			}
		}

		System.out.println(assignmentID + ":" + created);

		createWriter.print(assignmentID);
		createWriter.print("|");
		createWriter.print("123456Y");
		createWriter.print("|");
		createWriter.println(created);
	}

	private long addSubmission(long assignmentID, String studentNumber)
	{
		submissionsCreated++;

		long fileID = fileGen.addFileData("submission", submissionsCreated);

		String value = INSERT_SUBMISSION;
		value = value.replace("%1", String.valueOf(assignmentID));
		value = value.replace("%2", studentNumber);
		value = value.replace("%3", String.valueOf(fileID));
		writer.println(value);

		return submissionsCreated;
	}

	public void close() throws IOException
	{
		createWriter.close();
	}

}
